package com.tabbinder.server;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.tabbinder.client.Constants;

/**
 * Common methods of our servlets
 * 
 * @author Tatiana Kichkaylo
 */
public abstract class CommonServlet extends HttpServlet {

	/**
	 * Get current user. If null, fill in unauthorized response. This method is
	 * used by pretty much all servlets
	 * 
	 * @param resp
	 *            response to put the status code in
	 * @throws IOException
	 *             if writing to the response fails
	 */
	protected User getUser(HttpServletResponse resp) throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		if (user == null) {
			// Login required. This is a response to an internal method, so we
			// cannot just do redirect right from here - the JSON/data parser
			// would get upset. So, we send a status code and pass the URL in
			// the text. Plug-ins care only for the code
			resp.setStatus(Constants.STATUS_CODE_UNAUTHORIZED);
			resp.getWriter().append(
					userService.createLoginURL(Constants.HOME_URL));
		}
		return user;
	}
}
